package de.kraenksoft.android.cinemaExample.model;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.xmlpull.v1.XmlPullParserException;

import android.content.res.XmlResourceParser;

public class XmlTheaterFactory {

	Theater theater = new Theater();

	public Theater createTheater(XmlResourceParser xmlParser) {
		try {
			Movie movie = null;
			int eventType = xmlParser.getEventType();
			while (eventType != XmlResourceParser.END_DOCUMENT) {
				if (eventType == XmlResourceParser.START_TAG) {
					String tagName = xmlParser.getName();
					if (tagName.equals("movie")) {
						movie = new Movie();
						movie.setName(xmlParser.getAttributeValue(null, "name"));
					} else if (tagName.equals("screening")) {
						String timeString = xmlParser.getAttributeValue(null,
								"time");
						DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm");
						Date timeDate = df.parse(timeString);
						movie.addScreening(new Screening(timeDate));
					}
				} else if (eventType == XmlResourceParser.END_TAG) {
					String tagName = xmlParser.getName();
					if (tagName.equals("movie")) {
						theater.add(movie);
					}
				}
				eventType = xmlParser.next();
			}
			xmlParser.close();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return theater;
	}
}
